import { tiandituMapOSSUrl } from "~/common/fileConfig";

const mapKey = "c1151297cadf76d8dcd2d50833c0129c";
const mapUrl = `https://api.tianditu.gov.cn/api?v=4.0&tk=${mapKey}`;
// OSS 地图资源地址
const mapOSSUrl = tiandituMapOSSUrl;

// 设置超时时间
const limitLoadScript = 10 * 1000;

let mapContent = null;

// 异步加载天地图
export const asyncMapContent = async () => {
	if (mapContent) {
		return { map: mapContent };
	}

	const asyncLoadMap = new Promise((resolve) => {
		const scriptNode = document.createElement("script");
		scriptNode.charset = "utf-8";
		scriptNode.src = mapOSSUrl || mapUrl;
		document.head.appendChild(scriptNode);
		scriptNode.onload = function () {
			mapContent = window.T;
			resolve(mapContent);
		};
	});

	const content = await Promise.race([
		asyncLoadMap,
		new Promise((resolve, reject) => {
			setTimeout(() => {
				reject("天地图加载失败");
			}, limitLoadScript);
		}),
	]).catch((err) => {
		console.log("地图加载异常", err);
	});
	return content;
};
